const fsPromise = require("fs/promises");
const path = require("path");
// 遍历路径
exports.readdir = async function (rootdir, callback, deep = false) {
  // 不 catch，错误时将异常对象向上传递
  const dirs = await fsPromise.readdir(rootdir);

  if (dirs && dirs.length > 0) {
    for (let dir of dirs) {
      const absdir = path.join(rootdir, dir);
      const result = {
        err: null,
        name: dir,
        absdir,
        rootdir,
        isDirectory: null,
        stat: null,
      };
      const stat = await fsPromise.stat(absdir).catch((err) => {
        result.err = err;
        callback(result);
      });
      if (!stat) continue;
      const isDirectory = stat.isDirectory();
      if (deep && isDirectory) {
        exports.readdir(absdir, callback, true);
      }
      result.isDirectory = isDirectory;
      result.stat = stat;
      callback(result);
    }
  }
};
